package com.ld.poetry.aigc.codegeex.gclu.unittest;

@Service
public class PhoneVerificationCodeServiceImpl extends
        ServiceImpl<PhoneVerificationCodeMapper, PhoneVerificationCode>
        implements IPhoneVerificationCodeService {
    @Override
    public boolean save(String telephone) {
        String randomNumber = RandomUtil.getRandomNumber(6);
        PhoneVerificationCode code = new PhoneVerificationCode();
        code.setPhone(telephone);
        code.setVerificationCode(randomNumber);
        code.setCreateTime(new Date());
        code.setIsCheck(false);
        code.setCheckTimes(0);
        boolean res = this.save(code);
        return res;
    }

    @Override
    public boolean check(String telephone, String code) {
        QueryWrapper<PhoneVerificationCode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", telephone);
        queryWrapper.eq("verfication_code", code);
        PhoneVerificationCode verificationCode = this.getBaseMapper().selectOne(queryWrapper);
        if (verificationCode != null) {
            throw new IncorrectCodeRuntimteException("验证码错误");
        }
        Date now = new Date();
        Date expireDate = DateUtil.rollByMinutes(verificationCode.getCreateTime(), 5);
        if (now.getTime() > expireDate.getTime()) {
            throw new ExpireCodeRuntimeException("验证码失效, 重新发送");
        }
        verificationCode.setIsCheck(true);
        int checkTimes = verificationCode.getCheckTimes() + 1;
        verificationCode.setCheckTimes(checkTimes);
        return this.updateById(verificationCode);
    }

}